const cp=require('child_process')
const mongoose=require('mongoose')
const {resolve}=require('path')

const HtmlUrl=mongoose.model('HtmlUrl')
;(async ()=>{
    const script=resolve(__dirname,'../crawler/movie-list.js')

    const child=cp.fork(script,[])
    let invoked=false

    child.on('error',err=>{
        if(invoked)return
        invoked=true
        console.log(err)
    })
    child.on('exit',code=>{
        if(invoked)return
        invoked=true
        let err=code===0?null:new Error('exit code'+code)
    })
    child.on('message',data=>{
      data.forEach(async element => {
          let url=await HtmlUrl.findOne({
            htmlurl:element
          })
          if(!url){
              url=new HtmlUrl({htmlurl:element})
              await url.save() 
          }
      });

    })
})()